import { defineStore } from "pinia";
import { commentRoutes } from "../../router/routes";
import { ref } from "vue";
import { reqLogin, reqLogout, reqRegister } from "../../apis/user";
import { reqGetMemberProject, reqGetProject } from "../../apis/project";
import type { ProjectItem } from "../../apis/project/type";
import type { LoginRequest } from "../../apis/user/type";
import type { MainRoute } from "../../router/type";

let useUserStore = defineStore('user', () => {
  let menuRoutes = ref<MainRoute[]>(commentRoutes)
  let asyncRoutes = ref<MainRoute[]>([])
  let userName = ref<string>('')
  let password = ref<string>('')
  let id = ref<number>()
  let token = ref<string>('')
  let avator = ref<string>('')
  let role = ref<string>('')
  let email = ref<string>('')
  let status = ref<string>('')
  let projectData = ref<ProjectItem[]>([])
  let currentTitle = ref<string>('')

  const findRouteTitleById = (id: number) => {
    asyncRoutes.value.forEach((item: any) => {
      if (item.children.meta.id === id) {
        currentTitle.value = item.children.meta.title
      }
    });
    return undefined;
  };


  // 登录
  const userLogin = async (date: LoginRequest) => {
    const res = await reqLogin(date)
    if (res.code === 200) {
      token.value = res.data.token
      userName.value = res.data.user.username
      role.value = res.data.user.role
      email.value = res.data.user.email
      id.value = res.data.user.id
      status.value = res.data.user.status
      aboutAsyncRoutes()
      return 'ok'
    } else {
      return Promise.reject(new Error(res.msg))
    }
  }

  // 注册
  const userRegister = async (date: any) => {
    const res = await reqRegister(date)
    if (res.code === 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error(res.msg))
    }
  }

  // 退出
  const userLogout = async () => {
    const res = await reqLogout()
    if (res.code === 200) {
      token.value = ''
      userName.value = ''
      role.value = ''
      email.value = ''
      id.value = undefined
      return 'ok'
    }
  }

  const getAllMemberProject = async () => {
    const res = await reqGetMemberProject()
    if (res.code === 200) {
      projectData.value = res.data
      console.log(res.data)
    }
  }

  const createAsyncRouter = () => {
    asyncRoutes.value = []
    return projectData.value.map(item => {
      const transformed = {
        path: `/room/${item.id}`,
        name: `${item.id}room`,
        component: () => import('../../layout/index.vue'),
        redirect: `/room/myroom/${item.id}`,
        meta: {
          isShow: true,
        },
        children: [
          {
            path: `/room/myroom/${item.id}`,
            component: () => import('../../view/room/index.vue'),
            name: `${item.id}myroom`,
            meta: {
              title: item.name,
              isShow: true,
              icon: 'HelpFilled',
              id: item.id
            }
          }
        ]
      }
      return transformed
    })
  }



  const addAsyncRoutes = () => {
    const transformedRoutes = createAsyncRouter()
    transformedRoutes.forEach(route => {
      asyncRoutes.value.push(route)
    })
  }

  const aboutAsyncRoutes = async () => {
    await getAllMemberProject()
    createAsyncRouter()
    addAsyncRoutes()
  }
  return {
    menuRoutes,
    userName,
    token,
    avator,
    role,
    email,
    asyncRoutes,
    projectData,
    id,
    password,
    status,
    userLogin,
    userRegister,
    createAsyncRouter,
    reqGetProject,
    addAsyncRoutes,
    getAllMemberProject,
    userLogout,
    findRouteTitleById,
    aboutAsyncRoutes
  }

},
  {
    persist: true
  })

export default useUserStore